#include "hal_driver.h"
#include "cfg_param.h"
#include "hal_current.h"
#include "hal_temp.h"
#include "i2c.h"
#include "spi.h"
#include "common.h"
#include "sys_log.h"
#include "cfg_drive.h"
#include "hal_errorcode.h"
#include "hal_tlv.h"

float RealData = 0;

float tempSum = 0;
float tempResT = 0;
float tempSumCal = 0;

float pdCur7689Driver = 0;

uint16_t CurrentWri = 0;
HAL_StatusTypeDef sta = HAL_OK;

void HAL_CurrentDrivePinEnable(int lasernum){
    // fixbyme：TA通道读取ldon永远是低电平，因此在ta通道电流源打开状态下，再下发一次打开电流源指令会运行下面的if导致电流降为0
    GPIO_PinState state = (lasernum == LASER_NUMBER_CHAN_1 ? LASER_GPIO_READ_PIN(CH1_REG_LD_ON) : LASER_GPIO_READ_PIN(CH2_REG_LD_ON));

    // 关闭状态
    if (state == RESET)
    {
        if (lasernum == LASER_NUMBER_CHAN_1)
        {
            hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_1);
        }
        else if (lasernum == LASER_NUMBER_CHAN_2)
        {
#if MODEL_CHOICE == MODEL_LASER_TA
						//hal_TACurrentSlowChange(0, SAMPCUR_TYPE_WORK_CURRENT);
						hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_2);
            //hal_PDCurrentSlowChange(0, lasernum);
#elif MODEL_CHOICE == MODEL_LASER_DFB
            hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED, lasernum);
#endif
        }

        systick_delay_ms(5);

        // 打开电流源
        LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_REG_LD_EN : CH2_REG_LD_EN), GPIO_PIN_RESET);
    }

    SLOG_I("laser LaserNum %d HAL_CurrentDrivePinEnable state -- %s \t\r\n", lasernum, (state == RESET ? "is close but will open" : "is open"));
}

void HAL_CurrentDrivePinDisEnable(int lasernum){
    if (lasernum == LASER_NUMBER_CHAN_1)
    {
        hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_1);
    }
    else if (lasernum == LASER_NUMBER_CHAN_2)
    {
#if MODEL_CHOICE == MODEL_LASER_TA
				//hal_TACurrentSlowChange(0, SAMPCUR_TYPE_WORK_CURRENT);
				hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED, LASER_NUMBER_CHAN_2);
        //hal_PDCurrentSlowChange(0, lasernum);
#elif MODEL_CHOICE == MODEL_LASER_DFB
        hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED, lasernum);
#endif
    }

    systick_delay_ms(5);

    // 关闭电流源
    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_REG_LD_EN : CH2_REG_LD_EN), GPIO_PIN_SET);

    SLOG_I("laser LaserNum %d HAL_CurrentDrivePinDisEnable \t\r\n", lasernum);
}

void HAL_TempDrivePinEnable(int lasernum){
    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_REG_SHDN : CH2_REG_SHDN), GPIO_PIN_SET);

    SLOG_I("laser LaserNum %d HAL_TempDrivePinEnable \t\r\n", lasernum);
}

void HAL_TempDrivePinDisEnable(int lasernum){
    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_REG_SHDN : CH2_REG_SHDN), GPIO_PIN_RESET);

    SLOG_I("laser LaserNum %d HAL_TempDrivePinDisEnable \t\r\n", lasernum);
}

//PD6引脚置0或置1确定模式，恒流还是恒功率
//恒流也要显示pd电流
//电流获取
//i2c1是chan1，i2c2是chan2
//fix后不再需要i2c1，通过i2c2的四个通道来判断通道和电流
//sampcurtype确定是pd还是work
float HAL_ADC1119I2cReadCurrentReal(uint8_t lasernum, SampCurTypeEn SampCurType){
    //I2C_HandleTypeDef hi2cX = (lasernum == LASER_NUMBER_CHAN_1) ? hi2c1 : hi2c2;
		
		I2C_HandleTypeDef hi2cX = hi2c2;
		
		uint8_t chan_cmd_temp = 0x00;
		
		switch(lasernum){
			case LASER_NUMBER_CHAN_1:
				chan_cmd_temp = 0x6D;
				break;
			case LASER_NUMBER_CHAN_2:
				chan_cmd_temp = 0xAD;
				break;
		}
		
		if(SampCurType == SAMPCUR_TYPE_WORK_VOLTAGE){
			chan_cmd_temp = chan_cmd_temp + 0x20;
		}

    //uint8_t ConfigCmd[] = {0x40, (SampCurType == SAMPCUR_TYPE_PD_CURRENT) ? 0xAD : 0x6D, 0x08, 0x10};
		
		uint8_t ConfigCmd[] = {0x40, chan_cmd_temp, 0x08, 0x10};

    uint8_t ADS119RegData[2] = {0};
    HAL_StatusTypeDef status = HAL_OK;
    uint16_t TryCount = 0, status_drdy = ABNORMAL_STATE;
    float RealData = 0;

    /* fix by me :HAL_MAX_DELAY 优化一下  根据字节 * 传输速率 再乘以10倍来定 这个delay时间，不要用HAL_MAX_DELAY ADS1119_I2C_DELAY_TIME_LIMIT
       TA激光器不能用具体的时间，暂时还是用HAL_MAX_DELAY*/
    status = HAL_I2C_Master_Transmit(&hi2cX, ADS1119_CHIP_ADDRESS, &ConfigCmd[0], 2, HAL_MAX_DELAY);
    status = HAL_I2C_Master_Transmit(&hi2cX, ADS1119_CHIP_ADDRESS, &ConfigCmd[2], 1, HAL_MAX_DELAY);

    while (TryCount++ <= ADS1119_DRDY_WAIT_LIMIT)
    {
        if (GPIO_PIN_RESET == LASER_GPIO_READ_PIN((lasernum == LASER_NUMBER_CHAN_1) ? CH1_ADS1119_REG_DRDY : CH2_ADS1119_REG_DRDY))
        {
            status_drdy = NORMAL_STATE;
            break;
        }
    }

    status = HAL_I2C_Master_Transmit(&hi2cX, ADS1119_CHIP_ADDRESS, &ConfigCmd[3], 1, HAL_MAX_DELAY);
    status = HAL_I2C_Master_Receive(&hi2cX, ADS1119_CHIP_ADDRESS, (uint8_t *)&ADS119RegData, 2, HAL_MAX_DELAY);

    RealData = hal_ADS1119I2cCurrentRegtomA(Int8ToInt16BigEnd(ADS119RegData), lasernum, SampCurType);

    if ((status_drdy != NORMAL_STATE) || (status != HAL_OK))
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_LASER, l_ADC1119_Abnormal_Flag, lasernum, ABNORMAL_STATE);
    }

    return RealData;
}

/*void HAL_DAC5541SpiWriteCurrentReal(float current, int lasernum,SampCurTypeEn SampCurType){
    HAL_StatusTypeDef status = HAL_OK;
		
		//增加pd判断传参
    uint16_t CurrentWriteReg = hal_DAC5541SpiCurrentmAToReg(current, lasernum,SampCurType);
	
		CurrentWri = CurrentWriteReg;

    SPI_HandleTypeDef hspiX;

    hspiX = lasernum == LASER_NUMBER_CHAN_1 ? hspi1 : hspi2;

    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_AD5541_REG_NSS : CH2_AD5541_REG_NSS), GPIO_PIN_RESET);

    status = HAL_SPI_Transmit(&hspiX, (uint8_t *)&CurrentWriteReg, 1, DAC5541_SPI_DELAY_TIME_LIMIT);

		sta = status;
    
		LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_AD5541_REG_NSS : CH2_AD5541_REG_NSS), GPIO_PIN_SET);

    if (status != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_LASER, l_DAC5541_Abnormal_Flag, lasernum, ABNORMAL_STATE);
    }
}*/

void HAL_DAC5541SpiWriteCurrentReal(float current, int lasernum)
{
    HAL_StatusTypeDef status = HAL_OK;

    uint16_t CurrentWriteReg = hal_DAC5541SpiCurrentmAToReg(current, lasernum);

    SPI_HandleTypeDef hspiX;

    hspiX = lasernum == LASER_NUMBER_CHAN_1 ? hspi1 : hspi2;

    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_AD5541_REG_NSS : CH2_AD5541_REG_NSS), GPIO_PIN_RESET);

    status = HAL_SPI_Transmit(&hspiX, (uint8_t *)&CurrentWriteReg, 1, DAC5541_SPI_DELAY_TIME_LIMIT);

    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_AD5541_REG_NSS : CH2_AD5541_REG_NSS), GPIO_PIN_SET);

    if (status != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_LASER, l_DAC5541_Abnormal_Flag, lasernum, ABNORMAL_STATE);
    }
}

void HAL_DAC8830SpiWriteTempReal(float temp_real, int lasernum){
    HAL_StatusTypeDef status = HAL_OK;

    uint16_t RegRealData = hal_DAC8830SpiTempTToReg(temp_real);

    SPI_HandleTypeDef hspiy;

    hspiy = lasernum == LASER_NUMBER_CHAN_1 ? hspi3 : hspi5;

    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_DAC8830_REG_NSS : CH2_DAC8830_REG_NSS), GPIO_PIN_RESET);

    status = HAL_SPI_Transmit(&hspiy, (uint8_t *)&RegRealData, 1, DAC8830_SPI_DELAY_TIME_LIMIT);

    LASER_GPIO_WRITE_PIN((lasernum == LASER_NUMBER_CHAN_1 ? CH1_DAC8830_REG_NSS : CH2_DAC8830_REG_NSS), GPIO_PIN_SET);

    if (status != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_LASER, l_DAC8830_Abnormal_Flag, lasernum, ABNORMAL_STATE);
    }
}



float HAL_AD7689SpiReadTempOrTempCtrCurReal(uint16_t channel, uint8_t ad7689_model, uint8_t lasernum){
    HAL_StatusTypeDef status;

    // 换一个通道，需要重新配置寄存器，且前三次忽略
    uint16_t TempReg     = 0;
    uint16_t AD7689_WCfg = (uint16_t)AD7689_WCfg(channel);
    AD7689_WCfg <<= 2;
    float RealData = 0;
		float tempRes = 0;

    // 更改通道配置前AD7689_INVALID_COUNT次无效数据
    for (int i = 0; i < AD7689_LASER_MEAN_COUNT + AD7689_INVALID_COUNT; i++)
    {
        TempReg = 0;

        LASER_GPIO_WRITE_PIN(AD7689_REG_NSS, GPIO_PIN_SET);
        LASER_GPIO_WRITE_PIN(AD7689_REG_NSS, GPIO_PIN_RESET);
        status = HAL_SPI_TransmitReceive(&hspi4, (uint8_t *)&AD7689_WCfg, (uint8_t *)&TempReg, 1, AD7689_SPI_DELAY_TIME_LIMIT);
        LASER_GPIO_WRITE_PIN(AD7689_REG_NSS, GPIO_PIN_SET);
        systick_delay_us(AD7689_SAMP_DELAY);

        if (i >= AD7689_INVALID_COUNT)
        {
            if (ad7689_model == AD7689_LASER_TEMP_REGTOT)
            {
								tempRes = hal_ADC7689TempRegtoT(TempReg);
								tempResT = tempRes;
                RealData += tempRes;
								
            }
            else if (ad7689_model == AD7689_LASER_TEMPCTRCUR_REGTOT)
            {
                RealData += (hal_ADC7689TemptCtrCurRegToI(TempReg));
            }else if(ad7689_model == AD7689_LASER_PDPOWER_REGTOT)
						{
								pdCur7689Driver = hal_ADC7689PDPowerRegToI(TempReg);
								RealData += pdCur7689Driver;
						}
        }
    }

    if (status != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_LASER, l_ADC7689_Abnormal_Flag, lasernum, ABNORMAL_STATE);
    }
		
		tempSum = RealData;
		RealData = RealData / 10.00;

    return RealData;
}

void HAL_SetWorkingMode(int mode){
	if(!mode){
		//恒流模式
		HAL_GPIO_WritePin(WORKING_MODE_GPIO_Port,WORKING_MODE_Pin,GPIO_PIN_RESET);
	}else{
		//恒功率模式
		HAL_GPIO_WritePin(WORKING_MODE_GPIO_Port,WORKING_MODE_Pin,GPIO_PIN_SET);
	}
}

int HAL_GetWorkingMode(){
	return HAL_GPIO_ReadPin(WORKING_MODE_GPIO_Port,WORKING_MODE_Pin);
}